<template>
  <div id="mapView" class="map-view">
    <!-- 图层控制面板 -->
    <div class="layer-control-panel">
      <el-card class="layer-card">
        <div class="card-header">
          <h3>高速公路管理</h3>
          <p class="subtitle">您可以在地图上绘制高速公路路线并提交信息</p>
          <p class="instruction-text">双击地图上的高速公路可以查询和修改</p>
        </div>
        <el-collapse v-model="activeCollapse">
          <el-collapse-item title="图层显示控制" name="layers">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-checkbox
                v-model="layerVisibility.highway"
                @change="toggleLayerVisibility('highway')"
                >高速公路</el-checkbox
              >
            </el-space>
          </el-collapse-item>
          <el-collapse-item title="图层操作控制" name="operations">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-button type="primary" @click="startAddHighway" :disabled="isDrawing">
                <el-icon><Plus /></el-icon> 新增高速公路
              </el-button>
            </el-space>
          </el-collapse-item>
        </el-collapse>
      </el-card>
    </div>

    <!-- 高速公路属性表单对话框 -->
    <el-dialog
      v-model="highwayFormVisible"
      :title="formMode === 'add' ? '新增高速公路' : '编辑高速公路'"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="highwayForm"
        label-width="120px"
        :rules="highwayFormRules"
        ref="highwayFormRef"
      >
        <el-form-item label="高速公路编号" prop="highway_code">
          <el-input v-model="highwayForm.highway_code" placeholder="请输入高速公路编号"></el-input>
        </el-form-item>
        <el-form-item label="高速公路名称" prop="highway_name">
          <el-input v-model="highwayForm.highway_name" placeholder="请输入高速公路名称"></el-input>
        </el-form-item>
        <el-form-item label="车道数" prop="lanes">
          <el-select v-model="highwayForm.lanes" placeholder="请选择车道数" style="width: 100%">
            <el-option label="2" value="2"></el-option>
            <el-option label="4" value="4"></el-option>
            <el-option label="6" value="6"></el-option>
            <el-option label="8" value="8"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="路况状态" prop="status">
          <el-select v-model="highwayForm.status" placeholder="请选择路况状态" style="width: 100%">
            <el-option label="良好" value="良好"></el-option>
            <el-option label="一般" value="一般"></el-option>
            <el-option label="较差" value="较差"></el-option>
            <el-option label="维修中" value="维修中"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="限速值(km/h)" prop="speed_limit">
          <el-select
            v-model="highwayForm.speed_limit"
            placeholder="请选择限速值"
            style="width: 100%"
          >
            <el-option label="60" value="60"></el-option>
            <el-option label="80" value="80"></el-option>
            <el-option label="100" value="100"></el-option>
            <el-option label="120" value="120"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="高速公路等级" prop="highway_level">
          <el-select
            v-model="highwayForm.highway_level"
            placeholder="请选择高速公路等级"
            style="width: 100%"
          >
            <el-option label="一级" value="一级"></el-option>
            <el-option label="二级" value="二级"></el-option>
            <el-option label="三级" value="三级"></el-option>
            <el-option label="四级" value="四级"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelHighwayForm">取消</el-button>
          <el-button type="primary" @click="submitHighwayForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 高速公路属性查看对话框 -->
    <el-dialog
      v-model="highwayInfoVisible"
      title="高速公路信息"
      width="500px"
      :key="refreshHighwayKey"
    >
      <div v-if="selectedHighway">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="高速公路编号">{{
            selectedHighway.attributes.highway_code
          }}</el-descriptions-item>
          <el-descriptions-item label="高速公路名称">{{
            selectedHighway.attributes.highway_name
          }}</el-descriptions-item>
          <el-descriptions-item label="车道数">{{
            selectedHighway.attributes.lanes
          }}</el-descriptions-item>
          <el-descriptions-item label="路况状态">{{
            selectedHighway.attributes.status
          }}</el-descriptions-item>
          <el-descriptions-item label="限速值"
            >{{ selectedHighway.attributes.speed_limit }} km/h</el-descriptions-item
          >
          <el-descriptions-item label="高速公路等级">{{
            selectedHighway.attributes.highway_level || '一级'
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="highwayInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="editHighway">编辑</el-button>
          <el-button type="danger" @click="confirmDeleteHighway">删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteConfirmVisible" title="确认删除" width="300px">
      <p>{{ deleteConfirmMessage }}</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteConfirmVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, reactive, nextTick } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel.js'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol.js'
import Query from '@arcgis/core/rest/support/Query.js'
import gaodeLayer from '../utils/GaoDeBaseLayer'

type HighwayFormType = {
  highway_code: string
  highway_name: string
  lanes: string
  status: string
  speed_limit: string
  highway_level: string
}

let view: MapView | null = null
let highwayLayer: FeatureLayer | null = null
let sketchLayer: GraphicsLayer | null = null
let sketchViewModel: SketchViewModel | null = null
let tempGraphic: Graphic | null = null

// 图层可见性控制
const layerVisibility = ref({
  highway: true,
}) as any

// 控制折叠面板的展开状态
const activeCollapse = ref(['layers', 'operations'])
// 添加刷新标记
const refreshHighwayKey = ref(0)

// 表单相关
const highwayFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const highwayFormVisible = ref(false)
const formMode = ref<'add' | 'edit'>('add')
const isDrawing = ref(false)
const highwayInfoVisible = ref(false)
const deleteConfirmVisible = ref(false)
let selectedHighway: Graphic | null = null

// 删除确认相关
const deleteConfirmMessage = ref('')
const deleteType = ref<'highway'>('highway')

// 将响应式变量改回普通变量
let highwayList: Graphic[] = []

// 高速公路表单数据
const highwayForm = reactive<HighwayFormType>({
  highway_code: '',
  highway_name: '',
  lanes: '4',
  status: '良好',
  speed_limit: '100',
  highway_level: '一级',
})

// 高速公路表单验证规则
const highwayFormRules = {
  highway_code: [{ required: true, message: '请输入高速公路编号', trigger: 'blur' }],
  highway_name: [{ required: true, message: '请输入高速公路名称', trigger: 'blur' }],
  lanes: [{ required: true, message: '请选择车道数', trigger: 'change' }],
  status: [{ required: true, message: '请选择路况状态', trigger: 'change' }],
  speed_limit: [{ required: true, message: '请选择限速值', trigger: 'change' }],
  highway_level: [{ required: true, message: '请选择高速公路等级', trigger: 'change' }],
}

// 切换图层可见性
const toggleLayerVisibility = (layerType: string) => {
  if (layerType === 'highway' && highwayLayer) {
    highwayLayer.visible = Boolean(layerVisibility.value.highway)
  }
}

// 开始添加高速公路
const startAddHighway = () => {
  if (!view || !sketchViewModel) return

  isDrawing.value = true
  ElMessage.info('请在地图上绘制高速公路线路')

  // 开始绘制线
  sketchViewModel.create('polyline')
}

// 取消高速公路表单
const cancelHighwayForm = () => {
  highwayFormVisible.value = false
  resetHighwayForm()

  // 如果是添加模式，清除临时图形
  if (formMode.value === 'add' && tempGraphic && sketchLayer) {
    sketchLayer.remove(tempGraphic)
    tempGraphic = null
  }

  isDrawing.value = false
}

// 重置高速公路表单
const resetHighwayForm = () => {
  if (highwayFormRef.value) {
    highwayFormRef.value.resetFields()
  }

  highwayForm.highway_code = ''
  highwayForm.highway_name = ''
  highwayForm.lanes = '4'
  highwayForm.status = '良好'
  highwayForm.speed_limit = '100'
  highwayForm.highway_level = '一级'
}

// 提交高速公路表单
const submitHighwayForm = async () => {
  if (!highwayFormRef.value) return

  await highwayFormRef.value.validate(async (valid) => {
    if (valid) {
      if (formMode.value === 'add') {
        // 添加新高速公路
        addHighway()
      } else {
        // 更新高速公路
        updateHighway()
      }
    }
  })
}

// 添加新高速公路
const addHighway = () => {
  if (!tempGraphic || !highwayLayer) return

  // 创建新的高速公路图形
  const attributes = {
    highway_code: highwayForm.highway_code,
    highway_name: highwayForm.highway_name,
    lanes: highwayForm.lanes,
    status: highwayForm.status,
    speed_limit: highwayForm.speed_limit,
    highway_level: highwayForm.highway_level,
  }

  // 创建新的图形
  const newGraphic = new Graphic({
    geometry: tempGraphic.geometry,
    attributes: attributes,
  })

  // 添加到图层
  highwayLayer
    .applyEdits({
      addFeatures: [newGraphic],
    })
    .then((result) => {
      if (result.addFeatureResults.length > 0) {
        ElMessage.success('高速公路添加成功')
        highwayFormVisible.value = false
        resetHighwayForm()

        // 清除临时图形
        if (sketchLayer && tempGraphic) {
          sketchLayer.remove(tempGraphic)
          tempGraphic = null
        }

        isDrawing.value = false

        // 刷新高速公路列表
        loadHighwayList()
      } else {
        ElMessage.error('高速公路添加失败')
      }
    })
    .catch((error) => {
      console.error('添加高速公路出错:', error)
      ElMessage.error('高速公路添加失败')
    })
}

// 更新高速公路
const updateHighway = async () => {
  if (!highwayLayer || !selectedHighway) return

  try {
    // 查询要更新的图形
    const query = new Query()
    query.where = `OBJECTID = ${selectedHighway.attributes.OBJECTID}`
    query.outFields = ['*']

    const result = await highwayLayer.queryFeatures(query)
    if (result.features.length === 0) {
      ElMessage.error('未找到要更新的高速公路')
      return
    }

    // 更新属性
    const updatedGraphic = result.features[0]
    updatedGraphic.attributes.highway_code = highwayForm.highway_code
    updatedGraphic.attributes.highway_name = highwayForm.highway_name
    updatedGraphic.attributes.lanes = highwayForm.lanes
    updatedGraphic.attributes.status = highwayForm.status
    updatedGraphic.attributes.speed_limit = highwayForm.speed_limit
    updatedGraphic.attributes.highway_level = highwayForm.highway_level

    // 提交更新到服务
    const editResult = await highwayLayer.applyEdits({
      updateFeatures: [updatedGraphic],
    })

    if (editResult.updateFeatureResults.length > 0) {
      ElMessage.success('高速公路更新成功')
      highwayFormVisible.value = false
      resetHighwayForm()

      // 刷新高速公路信息
      refreshHighwayKey.value++
    } else {
      ElMessage.error('更新高速公路失败')
    }
  } catch (error) {
    console.error('更新高速公路出错:', error)
    ElMessage.error('更新高速公路失败')
  }
}

// 编辑高速公路
const editHighway = () => {
  if (!selectedHighway) return

  formMode.value = 'edit'

  // 填充表单数据
  const attrs = selectedHighway.attributes
  highwayForm.highway_code = attrs.highway_code || ''
  highwayForm.highway_name = attrs.highway_name || ''
  highwayForm.lanes = attrs.lanes || '4'
  highwayForm.status = attrs.status || '良好'
  highwayForm.speed_limit = attrs.speed_limit || '100'
  highwayForm.highway_level = attrs.highway_level || '一级'

  highwayInfoVisible.value = false
  highwayFormVisible.value = true
}

// 确认删除高速公路
const confirmDeleteHighway = () => {
  if (!selectedHighway) return

  deleteType.value = 'highway'
  deleteConfirmMessage.value = `确定要删除编号为 ${selectedHighway.attributes.highway_code} 的高速公路吗？`
  highwayInfoVisible.value = false
  deleteConfirmVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (deleteType.value === 'highway') {
    await deleteHighway()
  }
}

// 删除高速公路
const deleteHighway = async () => {
  if (!selectedHighway || !highwayLayer) return

  try {
    const result = await highwayLayer.applyEdits({
      deleteFeatures: [selectedHighway],
    })

    if (result.deleteFeatureResults.length > 0) {
      ElMessage.success('高速公路删除成功')
      selectedHighway = null
    } else {
      ElMessage.error('删除高速公路失败')
    }
  } catch (error) {
    console.error('删除出错:', error)
    ElMessage.error('删除失败')
  } finally {
    deleteConfirmVisible.value = false
  }
}

// 加载高速公路列表
const loadHighwayList = async () => {
  if (!highwayLayer) return

  try {
    const query = new Query()
    query.where = '1=1'
    query.outFields = ['OBJECTID', 'highway_code', 'highway_name']
    query.returnGeometry = false

    const result = await highwayLayer.queryFeatures(query)
    highwayList = result.features
  } catch (error) {
    console.error('加载高速公路列表出错:', error)
    ElMessage.error('加载高速公路列表失败')
  }
}

// 根据编号获取高速公路名称
const getHighwayNameByCode = (code: string) => {
  const highway = highwayList.find((h) => h.attributes.highway_code === code)
  return highway ? highway.attributes.highway_name : code
}

// 初始化地图
const initMap = async () => {
  try {
    const map = new Map({
      basemap: {
        baseLayers: [gaodeLayer],
      },
    })

    view = new MapView({
      container: 'mapView',
      map: map,
      center: [116.404, 39.915], // 北京中心点坐标
      zoom: 10,
    })

    // 创建高速公路图层
    highwayLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayManagemnetSystem/FeatureServer/0',
      outFields: ['*'],
    })

    // 添加图层到地图
    map.add(highwayLayer)

    // 创建绘图图层和工具
    sketchLayer = new GraphicsLayer()
    map.add(sketchLayer)

    sketchViewModel = new SketchViewModel({
      view: view,
      layer: sketchLayer,
      polylineSymbol: new SimpleLineSymbol({
        color: [0, 0, 255],
        width: 3,
      }),
    })

    // 监听绘图完成事件
    sketchViewModel.on('create', (event) => {
      if (event.state === 'complete') {
        tempGraphic = event.graphic

        if (event.tool === 'polyline') {
          highwayFormVisible.value = true
        }

        isDrawing.value = false
      }
    })

    // 监听点击事件，用于查询高速公路
    view.on('click', async (event) => {
      if (isDrawing.value) return

      // 在点击位置查询高速公路
      const response = await view.hitTest(event)
      const features = response.results?.filter(
        (result) => result.graphic.layer === highwayLayer
      )

      if (features && features.length > 0) {
        // 显示高速公路详情
        selectedHighway = features[0].graphic
        highwayInfoVisible.value = true
      }
    })

    // 加载高速公路列表
    await loadHighwayList()
  } catch (error) {
    console.error('初始化地图出错:', error)
    ElMessage.error('初始化地图失败')
  }
}

onMounted(() => {
  initMap()
})

onUnmounted(() => {
  if (view) {
    view = null
  }
})
</script>

<style scoped>
.map-view {
  width: 100%;
  height: 100%;
  position: relative;
}

.layer-control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
  width: 250px;
}

.layer-card {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
}

.card-header {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 15px;
}

.card-header h3 {
  margin: 0;
  margin-bottom: 5px;
}

.subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
  margin-bottom: 5px;
}

.instruction-text {
  font-size: 14px;
  color: #e6a23c;
  margin: 5px 0 0 0;
  font-weight: bold;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
